using System;
using System.Collections.Generic;
using Lucene.Net.Index;
using Lucene.Net.Search;
using LuceneSearch.ContactApp.Indexing;

namespace LuceneSearch.ContactApp.Searching
{
    public class EntityQueryExecutor<T> where T : class
    {
        private readonly IndexDirectoryProvider directoryProvider;

        public EntityQueryExecutor(IndexDirectoryProvider directoryProvider)
        {
            this.directoryProvider = directoryProvider;
        }

        public IEnumerable<int> QueryAndReturnIds(Query query)
        {
            var directory = directoryProvider.GetIndexDirectoryForType(typeof(T));

            if (!IndexReader.IndexExists(directory))
                return new int[0];

            var indexSearcher = new IndexSearcher(directory);
//            var hits = indexSearcher.Search(query, new RowSecurityFilter(new[]{1}));
            var hits = indexSearcher.Search(query);

            var resultIds = new List<int>();

            for (var i = 0; i <= hits.Length() - 1; i++)
            {
                var doc = hits.Doc(i);
                var idField = doc.GetField("Id");

                resultIds.Add(Convert.ToInt32(idField.StringValue()));
            }

            indexSearcher.Close();

            return resultIds;
        }        
    }
}